#!/usr/bin/env python
#coding=utf-8
import douban.service   
import urllib, urllister
from time import strptime, strftime 
                                     

# Please use your own api key instead. e.g. :
APIKEY = "559936f15cf6d88d00cba4d416e489a7"

client = douban.service.DoubanService(api_key=APIKEY) 

#--------------定义常量,后期放入单独类中------------------------------------
DATA_PATH = 'data/'   
SLEEP_TIME = 5
EVERY_DISPLAY_NUM = 8
    
class DoubanFriends:
    
    def __init__(self):    
        pass
    
    def get_friends_data(self,people):
        #用于存储在文本中的数据
        self.title_all = ''
        #用于判断是否是新增加的数据,0为旧数据,非0为新增加数据
        self.tmp_count = 1
        #用于存储返回新增加数据的list
        self.new_data_list = []
        #用户的类别,用于获取全部的资料.书,电影,音乐
        self.user_category = ['movie','music','book']
        
        for cat in self.user_category :
            cat_data = self.get_category_data(people,cat)
            #第一次存储后直接返回,避免重复循环浪费资源
            if(cat_data == 'saved'):
                return ''
            
            if self.tmp_count == EVERY_DISPLAY_NUM:
                return self.new_data_list
        return self.new_data_list
        
    def get_category_data(self,people,cat):
        try:
            feed = client.GetPeopleFeed("http://api.douban.com/people/"+people[0]+"/collection?cat="+cat)
        except  Exception, e:
            return ''
        
        try:
            file_data = open(DATA_PATH+people[0]+'.txt', 'rb').read()
        #初始化,第一次将全部数据写入文本
        except IOError:
            for cat in self.user_category :
                try:
                    feed_tmp = client.GetPeopleFeed("http://api.douban.com/people/"+people[0]+"/collection?cat="+cat)
                    for movie in feed_tmp.entry:
                        self.title_all += movie.title.text+'\n'
                        #print "%s" % (movie.title.text.decode('utf-8').encode('gb2312'))
                except  Exception, e:
                    pass
            self.save_data(self.title_all,people[0])
            return 'saved'
        
        file_data_list = file_data.split('\r\n')
        
        for movie in feed.entry:
            #print "%s" % (movie.title.text.decode('utf-8').encode('gb2312'))
            for data in file_data_list:
                if movie.title.text == data:
                    self.tmp_count = 0
            if self.tmp_count == 0:
                #print "%s" % (movie.title.text.decode('utf-8').encode('gbk'))
                self.tmp_count = 1
            else:
                self.save_data(movie.title.text+'\n',people[0])
                
                #日期转换
                parsed_date = strptime( movie.updated.text, '%Y-%m-%dT%H:%M:%S+08:00' )
                converted_date = strftime( '%Y-%m-%d %H:%M:00', parsed_date )             
                try:
                  self.new_data_list.append(people[1].decode('utf-8').encode('gbk')+"  "+movie.title.text.decode('utf-8').encode('gbk')+"  "+converted_date)
                except  Exception, e:
                  self.new_data_list.append(people[0]+"  "+movie.title.text.decode('utf-8').encode('gbk')+"  "+converted_date)
                self.tmp_count = self.tmp_count + 1
                 
            #当达到一定的数目时,跳出此循环,避免提示显示在屏幕的外面
            if self.tmp_count == EVERY_DISPLAY_NUM:
                return self.new_data_list
        
    
    def get_friends_name(self,username):
        #好友列表
        people = []        

        usock = urllib.urlopen("http://www.douban.com/people/"+username+"/contact_list")
        parser = urllister.URLLister()
        parser.feed(usock.read())
        parser.close()
        usock.close()
        
        for url_name in parser.urls_names: 
          #url_list = url[1].split('/')
          #print url
          #print "\r\n"
          try:
            url_list = url_name[1].split('/')
            if(url_list[1] == 'people'):
              people.append([url_list[2],url_name[2]])
              #print url_name[2].decode('utf-8').encode('gbk')
          except  Exception, e:
            pass  
        return people
    
    def get_username(self):
        username = open('setup.ini', 'rb').read()
        return username
        
    def save_data(self,data,people):
        logfile = open(DATA_PATH+people+'.txt', 'a') 
        logfile.write(data)
        logfile.close()   
        
            
            
def main():
    douban_friends = DoubanFriends()
    douban_friends.get_friends_data()
            
if __name__ == "__main__":
    main()